import socket
import threading

# UDP 服务器配置
SERVER_IP = "127.0.0.1"
SERVER_PORT = 5000

# 消息处理函数
def handle_message(data, addr):
    print(f"Received message from {addr}: {data}")
    # 处理消息逻辑，此处仅打印
    response = "Received your message: {}".format(data.decode())
    return response.encode()

# 创建 UDP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定套接字到本地地址和端口
sock.bind((SERVER_IP, SERVER_PORT))

# 创建并启动消息处理线程
def run_server():
    while True:
        # 接收消息
        data, addr = sock.recvfrom(1024)
        # 处理消息并发送回复
        response = handle_message(data, addr)
        sock.sendto(response, addr)

thread = threading.Thread(target=run_server)
thread.start()

# 服务器端程序运行提示
print(f"UDP Server is running on {SERVER_IP}:{SERVER_PORT}")
